﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Michsky.UI.ModernUIPack;
using UnityEngine.Networking;
using System.IO;
using DG.Tweening;

#region 佛祖保佑
/*
                   _ooOoo_
                  o8888888o
                  88" . "88
                  (| -_- |)
                  O\  =  /O
               ____/`---'\____
             .'  \\|     |//  `.
            /  \\|||  :  |||//  \
           /  _||||| -:- |||||-  \
           |   | \\\  -  /// |   |
           | \_|  ''\---/''  |   |
           \  .-\__  `-`  ___/-. /
         ___`. .'  /--.--\  `. . __
      ."" '<  `.___\_<|>_/___.'  >'"".
     | | :  `- \`.;`\ _ /`;.`/ - ` : | |
     \  \ `-.   \_ __\ /__ _/   .-` /  /
======`-.____`-.___\_____/___.-`____.-'======
                   `=---='
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            佛祖保佑       永无BUG
*/
#endregion

public class AppUpdate : MonoBehaviour
{
    private Toast toast;
    private ModalWindowManager appUpdate_modalWindowManager;
    private UIManagerModalWindow appUpdate_uIManagerModalWindow;

    private GameObject appUpdateBar_gameObject;
    private ProgressBar bar_progressBar;
    private CanvasGroup bar_canvasGroup;

    private AndroidJavaClass androidJavaClass;


    private void Awake()
    {
        toast = GetComponent<Toast>();
        appUpdate_modalWindowManager = GameObject.Find("Canvas/AppUpdate").GetComponent<ModalWindowManager>();
        appUpdate_uIManagerModalWindow = appUpdate_modalWindowManager.GetComponent<UIManagerModalWindow>();

        appUpdateBar_gameObject = GameObject.Find("/Canvas").transform.Find("AppUpdateBar").gameObject;
        bar_progressBar = appUpdateBar_gameObject.transform.Find("Bar").GetComponent<ProgressBar>();
        bar_canvasGroup = appUpdateBar_gameObject.transform.Find("Bar").GetComponent<CanvasGroup>();

        androidJavaClass = new AndroidJavaClass("com.aoyouzhe.qianfenzhilib.UnityToAndroid");
    }

    private void Start()
    {
        CheckUpdate();
    }

    private void CheckUpdate()
    {
        StartCoroutine(SendRequest());
    }

    /// <summary>
    /// 开启一个协程，发送请求
    /// </summary>
    /// <returns></returns>
    IEnumerator SendRequest()
    {
        yield return new WaitForSeconds(1.0f);

        UnityWebRequest uwr = UnityWebRequest.Get("https://qianfenzhi-1305646487.cos.ap-beijing.myqcloud.com/update.txt"); //创建UnityWebRequest对象
        yield return uwr.SendWebRequest();                                 //等待返回请求的信息
        if (uwr.isHttpError || uwr.isNetworkError)                         //如果其 请求失败，或是 网络错误
        {
            Debug.Log(uwr.error); //打印错误原因
        }
        
        
        if(uwr.isDone)//请求成功
        {
            Debug.Log("Get:请求成功");
            string _data = uwr.downloadHandler.text;
            string[] allLines = _data.Split('`');
            if (allLines[0].Split('=')[0] == "version")
            {
                if (!(allLines[0].Split('=')[1] == Application.version))
                {
                    toast.InvokeEvent("检测到有可更新内容！");
                    Debug.Log("检测到有可更新内容！");
                    appUpdate_modalWindowManager.OpenWindow();
                    appUpdate_modalWindowManager.descriptionText = allLines[2].Split('=')[1];
                    appUpdate_uIManagerModalWindow.description.text = allLines[2].Split('=')[1];
                    appUpdate_modalWindowManager.onConfirm.AddListener(() => {
                        Debug.Log("正在下载！path:" + allLines[1].Split('=')[1]);
                        StartCoroutine(InstallApk(allLines[1].Split('=')[1]));
                    });
                }
            }
        }
    }


    IEnumerator InstallApk(string path)
    {
        appUpdateBar_gameObject.SetActive(true);
        bar_canvasGroup.DOFade(1.0f, .5f).SetEase(Ease.InOutExpo);

        UnityWebRequest request = UnityWebRequest.Get(path);
        request.SendWebRequest();
        
        if (request.isHttpError || request.isNetworkError)                         //如果其 请求失败，或是 网络错误
        {
            toast.InvokeEvent("下载失败，请退出重进！");
            Debug.Log("下载失败，请退出重进！");
            yield break;
        }

        Debug.Log(request.downloadHandler.isDone);
        while (!request.downloadHandler.isDone)
        {
            bar_progressBar.currentPercent = request.downloadProgress * 100.0f;
            yield return 0;
        }

        if (request.downloadHandler.isDone)
        {
            bar_progressBar.currentPercent = 100.0f;
            bar_canvasGroup.DOFade(.0f, .5f).SetEase(Ease.InOutExpo).OnComplete(() => {
                appUpdateBar_gameObject.SetActive(false);
            });

            using (FileStream fs = new FileStream(MainController._startPath + "/qianfenzhi.apk", FileMode.Create))
            {
                byte[] data = request.downloadHandler.data;
                fs.Write(data, 0, data.Length);
            }

            androidJavaClass.CallStatic<bool>("InstallApp", MainController._startPath + "/qianfenzhi.apk");
        }
    }
}
